﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Facebook.Entity;
using Facebook.Components;
using System.Collections.ObjectModel;
using System.Collections.Generic;

/// <summary>
/// Summary description for IMadeThisService
/// </summary>
public class IMadeThisService
{
    FacebookService _fbService = new FacebookService();
    
    //private Collection<User> _friends;
    private HttpContext _httpContext;

    private const string FACEBOOK_API_KEY = "f35c2e5cdece9440a8972285e927d949";
    private const string FACEBOOK_SECRET = "9f40c058608894ebb78d39fdb7851c55";
    
    public User CurrentUser
    {
        get
        {
            return _fbService.GetUserInfo();
        }
    }

    public FacebookService FacebookService
    {
        get
        {
            return this._fbService;
        }
    }


    public static IMadeThisService Current
    {
        get
        {   
            return new IMadeThisService(HttpContext.Current);
        }
    }

    public Collection<User> Friends
    {
        get
        {            
            if(_httpContext.Session["FRIENDS"] == null)
                _httpContext.Session["FRIENDS"] = _fbService.GetFriends();

            return (Collection<User>)(_httpContext.Session["FRIENDS"]);
        }
    }

    public Collection<User> ApplicationFriends
    {
        get
        {
            if (_httpContext.Session["APPFRIENDS"] == null)
                _httpContext.Session["APPFRIENDS"] = _fbService.GetFriendsAppUsers();

            return (Collection<User>)(_httpContext.Session["APPFRIENDS"]);
        }
    }

	public IMadeThisService(HttpContext context)
	{
        _httpContext = context;     
        Initialize();               // Initialize - getting facebook parameters
        DbConnection.Connect();
	}

    public User GetFriend(string userID)
    {
        foreach (User friend in this.Friends)
        {
            if (friend.UserId == userID)
                return friend;         
        }

        return null;
    }


    public WorkItem AddAchievment(string title, string description, string link, int month, int year, bool hasImage)
    {
        if (month < 1 || month > 12)
            throw new ArgumentException("Month range should be between 1 to 12");

        DateTime date = DateTime.Parse(string.Format("1/{0}/{1}", month, year));

        //ReadOnlyCollection<WorkItem> _list = WorkItem.Create(DbConnection.ExecuteSelect("SELECT * FROM WorkItem"));
        WorkItem.AddNew(this.CurrentUser.UserId, title, description, link, date, hasImage);
        
        // Add to the Profile Page
        SetProfileFBML();

        return WorkItem.GetWorkItem(this.CurrentUser.UserId, title);
    }
    
    public WorkItem GetUserWorkItem(string title)
    {
        return WorkItem.GetWorkItem(this.CurrentUser.UserId, title);
    }

    public ReadOnlyCollection<WorkItem> GetFriendsWorkItems()
    {
        Collection<string> ids = new Collection<string>();

        foreach (User friend in this.Friends)
        {
            ids.Add(friend.UserId);
        }            

        if (ids.Count == 0)
            return new List<WorkItem>().AsReadOnly();

        string[] strIDs = new string[ids.Count];
        ids.CopyTo(strIDs, 0);

        return WorkItem.GetWorkItems(strIDs);
    }

    public ReadOnlyCollection<WorkItem> GetUserWorkItems()
    {
        return WorkItem.GetWorkItems(this.CurrentUser.UserId);
    }

    public ReadOnlyCollection<WorkItem> GetUserWorkItems(string userID)
    {
        return WorkItem.GetWorkItems(userID);
    }

    private void Initialize()
    {
        _fbService.ApplicationKey = FACEBOOK_API_KEY;
        _fbService.Secret = FACEBOOK_SECRET;
        _fbService.IsDesktopApplication = false;

        string sessionKey = _httpContext.Session["facebook_session_key"] as String;
        string userId = _httpContext.Session["facebook_userId"] as String;

        // When the user uses the facebook login page, the redirect back here will will have the auth_token in the query params
        string authToken = _httpContext.Request.QueryString["auth_token"];

        // We have already established a session on behalf of this user
        if (!String.IsNullOrEmpty(sessionKey))
        {
            _fbService.SessionKey = sessionKey;
            _fbService.UserId = userId;
        }
        // This will be executed when facebook login redirects to our page
        else if (!String.IsNullOrEmpty(authToken))
        {
            _fbService.CreateSession(authToken);
            _httpContext.Session["facebook_session_key"] = _fbService.SessionKey;
            _httpContext.Session["facebook_userId"] = _fbService.UserId;
            _httpContext.Session["facebook_session_expires"] = _fbService.SessionExpires;
        }
        // Need to login
        else
        {
            _httpContext.Response.Redirect(@"http://www.facebook.com/login.php?api_key=" + _fbService.ApplicationKey + @"&v=1.0");
        }
    }

    private void SetProfileFBML()
    {
        string fbml = string.Format("{0} has added new work to his 'imadethis' profile", this.CurrentUser.Name);
        _fbService.SetFBML(fbml);
    }

}
